# encoding=utf-8
import sys,os
import datetime
reload(sys)
import smtplib
from email.mime.text import MIMEText
sys.setdefaultencoding('utf-8')
import unittest
import TestCase
from BaseAndUnit import HTMLTestRunnerCN

#相对路径
testcase_path = ".\\..\\TestCase"
report_path = ".\\..\\Result\\report\\"
#--------------------创建测试---------------------
def creat_suite():
    uit = unittest.TestSuite()
    discover = unittest.defaultTestLoader.discover(testcase_path,pattern="*_case.py")
    for test_suite in discover:
        # print(test_suite)
        for test_case in test_suite:
            uit.addTest(test_case)
    return uit

#==============邮件接收者=================
mailreceivers=['15093131283@139.com']
#==============发送人邮箱=================
mail_host='smtp.163.com'
mail_port='25'
mail_user='15093131283@163.com'
mail_pass='yangdawei1990'
#=============发邮件功能=================
def send_mail(mailreceivers,file_new):
    '''
    :param mailreceivers:接收人列表
    :param file_new:文件名
    :return:true或者false
    '''
    f=open(file_new,'rb')
    mail_body=f.read()
    f.close()
    msg=MIMEText(mail_body,'html','utf-8')
    msg['Subject']='Appium自动化测试报告'
    msg['From']=mail_user
    msg['To']=';'.join(mailreceivers)
    try:
        s=smtplib.SMTP()
        s.connect(mail_host,mail_port)
        s.login(mail_user,mail_pass)
        s.sendmail(mail_user,mailreceivers,msg.as_string())
        s.close()
        return True
    except Exception as e:
        print(str(e))
        return False
#===================查找测试报告目录，生成测试报告==================
def new_report(testreport):
    lists=os.listdir(testreport)
    lists.sort(key=lambda fn:os.path.getatime(testreport+'\\'+fn))
    file_new=os.path.join(testreport,lists[-1])
    print(file_new)
    return file_new


#-----------------------创建测试、生成测试报告、发邮件-------------
suite = creat_suite()
dateCurrent = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')  # 现在
report_path=report_path+"appium_report_"+dateCurrent+".html"
fp = open(report_path,"wb")
runner = HTMLTestRunnerCN.HTMLTestRunner(stream=fp,title="测试结果",description="appium测试结果")
runner.run(suite)
fp.close()
filepath=new_report('./../Result/report/')
if send_mail(mailreceivers,filepath):
    print('发送邮件成功')
else:
    print("发送邮件失败")